package pers.vic.dubbo.common.filter;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pers.vic.dubbo.common.tool.DubboTools;

/**
 * 描述: dubbo  消费端filter， 加入traceId 信息(用于log4j日志链路追加，tranceId里包含sessionId 用于获取session信息)
 *
 * @author Vic.xu
 * @date 2022-01-24 10:04
 */
@Activate(group = CommonConstants.CONSUMER)
public class ConsumerTraceFilter implements Filter {

    private Logger logger = LoggerFactory.getLogger(ConsumerTraceFilter.class);

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        //RpcContext.getContext().setAttachment(DubboTools.TRACE_ID, tranceId);
        setAttachment(invocation);
        return invoker.invoke(invocation);
    }

    private void setAttachment(Invocation invocation){
        String tranceId = DubboTools.generateTranceId();
        logger.info("tranceId = {}", tranceId);
        invocation.setAttachment(DubboTools.TRACE_ID, tranceId);
    }
}
